import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Switch, Space } from 'antd';

interface EditShelfManageProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  shelfData: {
    id: number;
    shelfName: string;
    shelfNumber: string;
    boxNumber: string;
    skuType: number;
    skuNum: number;
  };
}

export const EditShelfManage: React.FC<EditShelfManageProps> = ({
  open,
  onCancel,
  onSuccess,
  shelfData
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [autoGenerate, setAutoGenerate] = useState(false);

  // 获取自动生成的编码
  const getAutoCode = async () => {
    try {
      const response = await fetch('http://localhost:5233/api/Comm/GetCode?code=HJ');
      const code = await response.text();
      if (code) {
        form.setFieldsValue({ shelfNumber: code });
      } else {
        alert('获取编码失败');
      }
    } catch (error) {
      alert('获取编码出错：' + error);
    }
  };

  // 处理开关变化
  const handleSwitchChange = (checked: boolean) => {
    setAutoGenerate(checked);
    if (checked) {
      getAutoCode();
    } else {
      form.setFieldsValue({ shelfNumber: '' });
    }
  };

  // 表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      // 构建请求数据
      const submitData = {
        id: shelfData.id,
        shelfName: values.shelfName,
        shelfNumber: values.shelfNumber,
        boxNumber: shelfData.boxNumber,
        skuType: shelfData.skuType,
        skuNum: shelfData.skuNum
      };

      console.log('提交的数据:', submitData);

      const response = await fetch('http://localhost:5233/api/ShelfManage/UpdShelfManageModel', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submitData)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('返回结果:', result);
      
      if (result.code === 200) {
        alert(result.message);
        onSuccess();
      } else {
        alert(result.message || '修改失败');
      }
    } catch (error) {
      console.error('错误详情:', error);
      if (error instanceof Error && error.message.includes('validation')) {
        return;
      }
      alert('提交失败：' + (error instanceof Error ? error.message : String(error)));
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时设置表单初始值
  useEffect(() => {
    if (open && shelfData) {
      form.setFieldsValue({
        shelfName: shelfData.shelfName,
        shelfNumber: shelfData.shelfNumber
      });
    }
  }, [open, shelfData, form]);

  return (
    <Modal
      title="修改货架"
      open={open}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width={500}
    >
      <Form
        form={form}
        layout="vertical"
        autoComplete="off"
      >
        <Form.Item
          name="shelfName"
          label="仓库"
          rules={[{ required: true, message: '请选择仓库' }]}
        >
          <Select placeholder="请选择仓库" style={{ width: '100%' }}>
            <Select.Option value="洛阳仓库">洛阳仓库</Select.Option>
            <Select.Option value="长安仓库">长安仓库</Select.Option>
            <Select.Option value="石家庄仓库">石家庄仓库</Select.Option>
            <Select.Option value="北京仓库">北京仓库</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="货架编号"
          style={{ marginBottom: 24 }}
        >
          <Space.Compact style={{ display: 'flex' }}>
            <Form.Item
              name="shelfNumber"
              noStyle
              rules={[{ required: true, message: '请输入货架编号' }]}
            >
              <Input 
                placeholder="请输入货架编号" 
                disabled={autoGenerate}
                style={{ flex: 1 }}
              />
            </Form.Item>
            <Switch
              checkedChildren="自动"
              unCheckedChildren="手动"
              checked={autoGenerate}
              onChange={handleSwitchChange}
              style={{ marginLeft: 8 }}
            />
          </Space.Compact>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditShelfManage; 